package com.milk.nettylearn.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.milk.nettylearn.nio.ByteBufferUtil.debugRead;

@Slf4j
public class NoBlockServer {
    public static void main(String[] args) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(100);

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        // 设置为非阻塞
        serverSocketChannel.configureBlocking(false);

        List<SocketChannel> list = new ArrayList<>();
        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            if(socketChannel != null){
                socketChannel.configureBlocking(false);
                log.debug("connected .....");
                list.add(socketChannel);
            }


            for (SocketChannel channel : list) {
                int read = channel.read(buffer);
                if(read != 0){
                    // 转换为读模式
                    buffer.flip();
                    debugRead(buffer);
                    // 转换为读模式
                    buffer.clear();
                    log.debug("read after");
                }
            }

        }
    }
}
